import { onMounted, onUnmounted } from 'vue'

// 快捷键组合类
export class ShortcutManager {
  constructor() {
    this.shortcuts = new Map()
    this.handleKeyDown = this.handleKeyDown.bind(this)
  }

  // 注册快捷键
  register(keys, callback, description = '') {
    const keyString = this.normalizeKeys(keys)
    this.shortcuts.set(keyString, { callback, description })
  }

  // 注销快捷键
  unregister(keys) {
    const keyString = this.normalizeKeys(keys)
    this.shortcuts.delete(keyString)
  }

  // 规范化按键字符串
  normalizeKeys(keys) {
    return keys.toLowerCase()
      .split('+')
      .map(key => key.trim())
      .sort()
      .join('+')
  }

  // 处理键盘事件
  handleKeyDown(event) {
    const keys = []

    if (event.ctrlKey || event.metaKey) keys.push('ctrl')
    if (event.altKey) keys.push('alt')
    if (event.shiftKey) keys.push('shift')

    // 添加主键
    const mainKey = event.key.toLowerCase()
    if (!['control', 'alt', 'shift', 'meta'].includes(mainKey)) {
      keys.push(mainKey)
    }

    const keyString = keys.sort().join('+')
    const shortcut = this.shortcuts.get(keyString)

    if (shortcut) {
      event.preventDefault()
      shortcut.callback(event)
    }
  }

  // 启动监听
  start() {
    document.addEventListener('keydown', this.handleKeyDown)
  }

  // 停止监听
  stop() {
    document.removeEventListener('keydown', this.handleKeyDown)
  }

  // 获取所有快捷键
  getAll() {
    return Array.from(this.shortcuts.entries()).map(([keys, { description }]) => ({
      keys,
      description
    }))
  }
}

// 创建全局快捷键管理器
const shortcutManager = new ShortcutManager()

// Vue组合式函数
export function useShortcuts(shortcuts = {}) {
  onMounted(() => {
    // 注册快捷键
    Object.entries(shortcuts).forEach(([keys, config]) => {
      const callback = typeof config === 'function' ? config : config.callback
      const description = typeof config === 'object' ? config.description : ''
      shortcutManager.register(keys, callback, description)
    })

    // 启动监听
    shortcutManager.start()
  })

  onUnmounted(() => {
    // 注销快捷键
    Object.keys(shortcuts).forEach(keys => {
      shortcutManager.unregister(keys)
    })
  })

  return {
    registerShortcut: shortcutManager.register.bind(shortcutManager),
    unregisterShortcut: shortcutManager.unregister.bind(shortcutManager),
    getAllShortcuts: shortcutManager.getAll.bind(shortcutManager)
  }
}

// 默认的全局快捷键
export const globalShortcuts = {
  'ctrl+s': {
    callback: (event) => {
      console.log('保存操作')
      // 可以触发全局保存事件
    },
    description: '保存当前工作'
  },
  'ctrl+z': {
    callback: (event) => {
      console.log('撤销操作')
    },
    description: '撤销上一步操作'
  },
  'ctrl+y': {
    callback: (event) => {
      console.log('重做操作')
    },
    description: '重做操作'
  },
  'f11': {
    callback: (event) => {
      console.log('全屏切换')
    },
    description: '切换全屏模式'
  },
  'escape': {
    callback: (event) => {
      console.log('取消当前操作')
    },
    description: '取消当前操作'
  }
}

export default shortcutManager
